package com.doeis.manage.action;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.doeis.core.SuperAction;
import com.doeis.core.bean.Msg;
import com.doeis.manage.bean.Catalog;
import com.doeis.manage.bean.Item;
import com.doeis.manage.bean.Page;
import com.doeis.manage.service.CatalogService;
import com.doeis.manage.service.ItemService;
import com.doeis.manage.service.PageService;
import com.doeis.tools.DateHelper;
import com.doeis.tools.HashKit;
import com.doeis.tools.StringHelper;

/**
 * 
 * @author wxy
 * @date 2016-1-6
 */
@WebServlet(urlPatterns = "/item/*")
public class ItemAction extends SuperAction {

	private static final long serialVersionUID = 1L;

	private ItemService itemService = new ItemService();
	private CatalogService catalogService = new CatalogService();
	private PageService pageService = new PageService();

	@Override
	protected void doRequest(String methodName, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean login = checkSession(request, response);
		if ("index".equals(methodName)) {
			if (login) {
				toIndex(request, response);
			} else {
				toPage("index", "index", request, response);
			}
		} else if ("edit".equals(methodName)) {
			if (login) {
				// edit(methodName,request, response);
			} else {
				toPage("index", "index", request, response);
			}
		} else if ("show".equals(methodName)) {
			show(methodName, request, response);
		} else if ("add".equals(methodName)) {
			if (login) {
				add(methodName, request, response);
			} else {
				toPage("index", "index", request, response);
			}
		} else if ("doAdd".equals(methodName)) {
			if (login) {
				doAdd(methodName, request, response);
			} else {
				toPage("index", "index", request, response);
			}
		} else if ("ajaxDelete".equals(methodName)) {
			if (login) {
				ajaxDelete(methodName, request, response);
			} else {
				toPage("index", "index", request, response);
			}
		} else if ("pass".equals(methodName)) {
			pass(methodName, request, response);
		} else {
			toPage(methodName, "item", request, response);
		}
	}

	private void pass(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			String item_id = request.getParameter("item_id");
			String password = request.getParameter("password");

			if (StringHelper.isNull(item_id)) {
				item_id = "-1";
			}
			Item item = itemService.findById(Integer.parseInt(item_id));
			if (item != null && item.getPassword().equals(HashKit.md5(password))) {
				request.getSession().setAttribute("passed", Boolean.TRUE);
				response.sendRedirect("/item/show?item_id=" + item_id);
			} else {
				response.sendRedirect("/item/pwd?item_id=" + item_id);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void add(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			String item_id = request.getParameter("item_id");
			if (StringHelper.isNotNull(item_id)) {
				Item item = itemService.findById(Integer.parseInt(item_id));
				request.setAttribute("item", item);
			}
			toPage(methodName, "item", request, response);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void ajaxDelete(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			Msg msg = new Msg(false, "删除失败");
			String item_id = request.getParameter("item_id");
			String password = request.getParameter("password");

			if (StringHelper.isNotNull(item_id) && StringHelper.isNotNull(password)
					&& getLoginUser(request).getPassword().equals(HashKit.md5(password))) {
				itemService.delete(Integer.parseInt(item_id));
				msg.setStatus(true);
				msg.setMsg("删除成功");
			}
			sendJsonObject(msg, response);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void show(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			String item_id = request.getParameter("item_id");
			String keyword = request.getParameter("keyword");
			Item item = itemService.findById(Integer.parseInt(item_id));
			request.setAttribute("item", item);
			if (item != null && StringHelper.isNotNull(item.getPassword()) && !item.getUid().equals(getUserid(request))) {
				Boolean passed = (Boolean) request.getSession().getAttribute("passed");
				if (!Boolean.TRUE.equals(passed)) {
					response.sendRedirect("/item/pwd?item_id=" + item_id);
					return;
				}
			}
			boolean isMe = (item != null && getUserid(request) == item.getUid());
			List<Catalog> catalogs = catalogService.list(Integer.parseInt(item_id), keyword);
			List<Page> pages = null;
			for (Catalog catalog : catalogs) {
				pages = pageService.list(catalog.getId());
				catalog.setPages(pages);
			}
			request.setAttribute("isMe", isMe);
			request.setAttribute("catalogs", catalogs);
			toPage(methodName, "item", request, response);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doAdd(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			String item_id = request.getParameter("item_id");
			String item_name = request.getParameter("item_name");
			String item_description = request.getParameter("item_description");
			String password = request.getParameter("password");
			if (StringHelper.isNotNull(item_id)) {
				Item item = itemService.findById(Integer.parseInt(item_id));
				if (item != null) {
					item.setItem_description(item_description);
					item.setItem_name(item_name);
					if (StringHelper.isNotNull(password)) {
						item.setPassword(HashKit.md5(password));
					}else{
						item.setPassword(null);
					}
					itemService.update(item);
					response.sendRedirect("/item/show?item_id=" + item_id);
				} else {
					toPage("index", "item", request, response);
				}
			} else {
				Item item = new Item();
				item.setAddTime(DateHelper.currentDateTime());
				item.setItem_description(item_description);
				item.setItem_name(item_name);
				if (StringHelper.isNotNull(password)) {
					item.setPassword(HashKit.md5(password));
				}else{
					item.setPassword(null);
				}
				item.setUid(getUserid(request));
				item.setUsername(getLoginUser(request).getUsername());
				int id = itemService.add(item);
				response.sendRedirect("/item/show?item_id=" + id);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 跳转到管理页面
	 * 
	 * @Title: toIndex
	 * @data:2014-1-6上午09:40:37
	 * @author:xieyan
	 *
	 * @param request
	 * @param response
	 */
	private void toIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			int user_id = getUserid(request);
			List<Item> list = itemService.list(user_id);
			request.setAttribute("list", list);
			request.getRequestDispatcher(PAGE_PATH + "/item/index.jsp").forward(request, response);
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

}
